package org.i1510.common.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.i1510.common.utils.web.ResultMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class BaseController {
	private static final Logger logger = LoggerFactory
			.getLogger(BaseController.class);

	/**
	*@Author Rambo
	*@Desc：异常处理机制
	*@param ex
	*@param request
	*@return TODO
	*@Version  BaseController.java,v 1.1 2014-9-12 下午2:42:23 
	*/
	@ExceptionHandler(Exception.class)
	public String handleException(Exception ex, HttpServletRequest request) {
		ResultMapper mapper = ResultMapper.generateFailure();
		Map<Object, Object> model = new HashMap<Object, Object>();
		if (ex instanceof MaxUploadSizeExceededException) {
			mapper.appendResult("message", "文件应不大于 "+ getFileKB(((MaxUploadSizeExceededException) ex)	.getMaxUploadSize()));
		} else {
			mapper.appendResult("message", "不知错误: "+ex.getMessage());
		}
		return mapper.toJson();
	}

	private String getFileKB(long byteFile) {
		if (byteFile == 0)
			return "0KB";
		long kb = 1024;
		return "" + byteFile / kb + "KB";
	}

	private String getFileMB(long byteFile) {
		if (byteFile == 0)
			return "0MB";
		long mb = 1024 * 1024;
		return "" + byteFile / mb + "MB";
	}

}
